Skip to main content

路由守卫是什么?

vue-router提供的路由守卫主要用来通过跳转或取消的方式守卫导航。

路由守卫有三种:全局路由守卫、组件路由守卫(局部路由)、独享路由守卫


全局路由守卫:

  • 全局前置守卫router.beforeEach((to,from,next)=>{})
  • 全局后置守卫:router.afterEach((to, from) => {})

全局前置守卫

  1. 在 router.js 路由文件中处理
  2. 跳转到指定路由在reouter.beforeEach进行守卫
const router = new VueRouter({ ... })

reouter.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
//路由元信息:to.matched.some
store.dispatch('checkLogin').then(isLogin => {
if (!isLogin) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
})
} else {
next() //确保一定要调用next()
}
})

组件路由守卫(局部路由)

  • 组件路由到达守卫:beforeRouteEnter:(to,from,next)=>{}
  • 组件路由离开守卫:beforeRouteLeave:(to,from,next)=>{}
  • 组件路由更新守卫:beforeRouteUpdate:(to,from,next)=>{}

组件离开守卫(beforeRouteLeave)

  • 清除当前组件中的定时器
  • 当页面中有未关闭的窗口, 或未保存的内容时, 阻止页面跳转 / 弹出一个提示窗口
  • 保存相关内容到 Vuex 中或 Session 中

组件路由更新守卫

当使用路由参数时,例如从 /user/foo 导航到 /user/bar,原来的组件实例会被复用,全局路由守卫则失效,想对路由参数的变化作出响应的话,可以使用beforeRouteUpdate 监测对象变化

const Foo = {
template: `...`,
beforeRouteUpdate(to, from, next) {
// 在当前路由改变,但是该组件被复用时调用
// 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
// 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
// 可以访问组件实例 `this`
}
}

路由独享守卫

  • 路由独享离开守卫:beforeEnter:(to,from,next)=>{}

与全局路由守卫用法一致,但是只能针对一个页面使用


参考文章